<template>
  <div class="no-background-container">
    <el-affix :offset="62">
      <div class="qs-y-table-header">
        <div class="header-label">
          <div class="header-label-title">{{ moduleName }}</div>
        </div>
        <div class="header-query">
          <div class="header-query-buttons">
            <el-button type="primary" @click="handleAdd">新增审批</el-button>
            <el-button type="primary" @click="getList">刷新</el-button>
          </div>
          <query-form-component
            :list-loading="listLoading"
            :query-form="queryForm"
            :search-params="searchParams"
            @submit="queryData"
            @update:query-form="updateQueryForm"
          />
        </div>
      </div>
    </el-affix>

    <tree-table
      :loading="listLoading"
      :table-data="tableData"
      @add-child="handleAddChild"
      @config="handleConfig"
      @delete="handleDelete"
      @edit="handleEdit"
      @update:post="handlePostChange"
    />

    <el-dialog v-model="showFormDialog" :title="isEditMode ? '编辑' : '新增'" width="500px">
      <el-form ref="formRef" label-width="100px" :model="form" :rules="rules">
        <el-form-item label="审批名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入审批名称" />
        </el-form-item>
        <el-form-item label="审批人部门" prop="deptId">
          <tree-select v-model="form.deptId" api="/api/department" placeholder="请选择部门" />
        </el-form-item>
        <el-form-item label="审批人职务" prop="postsId">
          <el-select v-model="form.postsId" clearable :loading="postsLoading" placeholder="请选择职务">
            <el-option v-for="item in postsList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showFormDialog = false">取消</el-button>
          <el-button type="primary" @click="handleFormSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { onBeforeMount, ref } from 'vue'
import TreeTable from './components/TreeTable.vue'
import { moduleName, searchParams } from './config'
import { addApprovalProcess, deleteApprovalProcess, getParentApprovalProcess, updateApprovalProcess } from '/@/api/approval'
import type { ApprovalProcess, ApprovalProcessParams } from '/@/api/approval/types'
import TreeSelect from '/@/components/TreeSelect/index.vue'
import request from '/@/utils/request'

const tableData = ref<ApprovalProcess[]>([])
const showFormDialog = ref(false)
const isEditMode = ref(false)
const form = ref<Partial<ApprovalProcess>>({})
const formRef = ref<FormInstance>()
const listLoading = ref(false)
const postsLoading = ref(false)
const postsList = ref<{ label: string; value: string }[]>([])

interface QueryForm {
  page: number
  limit: number
  name?: string
  [key: string]: any
}

const queryForm = ref<QueryForm>({
  page: 1,
  limit: 20,
  activityId: localStorage.getItem('hongyouActId'),
})

const rules: FormRules = {
  name: [{ required: true, message: '请输入审批名称', trigger: 'blur' }],
  deptId: [{ required: true, message: '请选择部门', trigger: 'change' }],
  postsId: [{ required: true, message: '请选择职务', trigger: 'change' }],
}

// 获取列表数据
const getList = async () => {
  listLoading.value = true
  try {
    const data = await getParentApprovalProcess()
    if (data?.code === 0 && data?.result) {
      tableData.value = data.result
    }
  } catch {
    ElMessage.error('获取数据失败')
  } finally {
    listLoading.value = false
  }
}

// 获取职务列表
const getPostsList = async () => {
  postsLoading.value = true
  try {
    const data = await request({
      url: '/api/posts/all',
      method: 'get',
    })
    if (data?.code === 0 && data?.result) {
      postsList.value = data.result.map((item: any) => ({
        label: item.name,
        value: item.id,
      }))
    }
  } catch {
    ElMessage.error('获取职务列表失败')
  } finally {
    postsLoading.value = false
  }
}

// 配置审批流程
const handleConfig = (row: ApprovalProcess) => {
  console.log('配置审批流程', row)
}

// 新增
const handleAdd = () => {
  isEditMode.value = false
  form.value = {
    pId: 0,
  }
  showFormDialog.value = true
  getPostsList()
}

// 编辑
const handleEdit = (row: ApprovalProcess) => {
  isEditMode.value = true
  form.value = {
    ...row,
    pId: row.pId || 0,
  }
  showFormDialog.value = true
  getPostsList()
}

// 删除
const handleDelete = async (row: ApprovalProcess) => {
  try {
    await ElMessageBox.confirm('确认删除该审批流程吗？', '提示', {
      type: 'warning',
    })
    const data = await deleteApprovalProcess(String(row.id))
    if (data?.code === 0) {
      ElMessage.success('删除成功')
      await getList()
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
      await getList()
    }
  }
}

// 处理职务变更
const handlePostChange = async (row: ApprovalProcess, value: string | number) => {
  try {
    const updatedData: ApprovalProcessParams = {
      ...row,
      postsId: String(value),
    }
    const { data } = await updateApprovalProcess(String(row.id), updatedData)
    if (data?.code === 0) {
      ElMessage.success('职务更新成功')
      await getList()
    }
  } catch {
    ElMessage.error('职务更新失败')
    await getList()
  }
}

// 提交表单
const handleFormSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()

    const submitData: ApprovalProcessParams = {
      pId: form.value.pId || 0,
      name: form.value.name || '',
      remark: form.value.remark || '',
      postsId: form.value.postsId || '',
      deptId: form.value.deptId || '',
      activityId: form.value.activityId || null,
    }

    if (isEditMode.value) {
      if (!form.value.id) {
        ElMessage.error('编辑数据缺少ID')
        return
      }
      submitData.id = form.value.id
      const data = await updateApprovalProcess(String(submitData.id), submitData)
      if (data?.code === 0) {
        ElMessage.success('修改成功')
        showFormDialog.value = false
        form.value = {}
        await getList()
      }
    } else {
      const data = await addApprovalProcess(submitData)
      if (data?.code === 0) {
        ElMessage.success('新增成功')
        showFormDialog.value = false
        form.value = {}
        await getList()
      }
    }
  } catch {
    ElMessage.error(isEditMode.value ? '修改失败' : '新增失败')
  }
}

// 查询数据
const queryData = () => {
  queryForm.value.page = 1
  getList()
}

// 更新查询表单
const updateQueryForm = (val: QueryForm) => {
  queryForm.value = val
}

// 新增子级审批
const handleAddChild = (row: ApprovalProcess) => {
  isEditMode.value = false
  form.value = {
    pId: row.id,
  }
  showFormDialog.value = true
  getPostsList()
}

// 组件挂载前初始化
onBeforeMount(() => {
  getList()
})
</script>

<style scoped>
.el-dialog__body .el-form:not(.el-form--inline):not(.el-form--label-top) .el-form-item:last-child {
  margin-bottom: 15px;
}
</style>
